import React, { useState, useEffect } from 'react';
import styles from './index.less';
import { Button, Input, Table, Select, Modal, message, Form } from 'antd';
import CardCommon from '@/compontents/cardCommon';
import lhTool from 'lh-tool';
import api from '@/http/api';
import { PlusOutlined, ExclamationCircleOutlined } from '@ant-design/icons';
import md5 from 'md5';

const {
  uSchoolManageList,
  uSchoolManageAdd,
  uSchoolManageDelete,
  uSchoolManageUpdate,
  uSchoolEnter,
} = api;
const { Option } = Select;
const { confirm } = Modal;

export default (props: any) => {
  // 表格
  const [list, setList] = useState([]);
  const [pageNo, setPageNo] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  // 学校id
  const { schoolId } = JSON.parse(sessionStorage.info).userInfo;
  // 学校列表
  const [schoolList, setSchoolList] = useState([]);
  // 新增编辑弹框
  const [showAdd, setShowAdd] = useState(false);
  // 是否新增
  const [isAdd, setIsAdd] = useState(true);
  const [initData, setInitData]: any = useState({});
  // 表单样式
  const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 16 },
  };
  const tailLayout = {
    wrapperCol: { offset: 17, span: 16 },
  };
  const columns: any = [
    {
      title: '序号',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      width: 100,
      render: (text: any, record: any, index: any) => `${index + 1}`,
    },
    {
      title: '用户名',
      dataIndex: 'userName',
      key: 'userName',
    },
    {
      title: '昵称',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: '学校名称',
      dataIndex: 'schoolName',
      key: 'schoolName',
    },
    {
      title: '操作',
      dataIndex: 'handle',
      width: 200,
      render: (v1: any, v2: any) => (
        <div>
          <Button
            onClick={() => {
              add(v2);
            }}
            size="small"
            type="primary"
          >
            编辑
          </Button>
          <Button
            onClick={() => {
              deleteR(v2);
            }}
            style={{ marginLeft: 10 }}
            size="small"
            danger
            type="primary"
          >
            删除
          </Button>
        </div>
      ),
    },
  ];
  useEffect(() => {
    getList(pageNo, pageSize, schoolId);
  }, []);
  // 表格列表
  const getList = (pageNo: Number, pageSize: Number, schoolId: Number) => {
    uSchoolManageList({
      pageNo,
      pageSize,
      schoolId,
      type: 3,
    }).then((res: any) => {
      const { list, total } = res.data;
      setList(list);
      setTotal(total);
    });
  };
  // 分页改变
  const pageChange = (pageNo: any, pageSize: any) => {
    setPageNo(pageNo);
    setPageSize(pageSize);
    getList(pageNo, pageSize, schoolId);
  };
  const handleCancel = () => {
    setShowAdd(false);
  };
  // 点击新增编辑
  const add = (row: any) => {
    const { userName } = row;
    setIsAdd(userName ? false : true);
    if (userName) {
      // 编辑
      setShowAdd(true);
      setInitData(row);
    } else {
      // 新增
      setShowAdd(true);
    }
  };
  const onFinish = (v: any) => {
    const { name, password, userName } = v;
    if (isAdd) {
      uSchoolManageAdd({
        name,
        password: md5(password),
        userName,
        schoolId,
        type: 3,
      }).then(_ => {
        setShowAdd(false);
        getList(pageNo, pageSize, schoolId);
      });
    } else {
      const { manageId } = initData;
      uSchoolManageUpdate({
        name,
        password: password ? md5(password) : '',
        manageId,
      }).then(_ => {
        setShowAdd(false);
        getList(pageNo, pageSize, schoolId);
      });
    }
  };
  const deleteR = (row: any) => {
    const { manageId } = row;
    confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '确定删除吗？',
      onOk() {
        uSchoolManageDelete({ manageId }).then(_ => {
          getList(pageNo, pageSize, schoolId);
        });
      },
    });
  };
  return (
    <CardCommon>
      <div className={styles.wrap}>
        <div className={styles.tool}>
          <Button
            onClick={() => {
              add({});
            }}
            type="primary"
          >
            新增
          </Button>
        </div>
        <Table
          dataSource={list}
          columns={columns}
          pagination={{
            showQuickJumper: true,
            total,
            size: 'small',
            onChange: pageChange,
            showTotal: () => {
              return `总共 ${total} 条记录`;
            },
          }}
        />
        <Modal
          title={isAdd ? '新增校园活动运营者' : '编辑校园活动运营者'}
          visible={showAdd}
          onCancel={handleCancel}
          footer={null}
          destroyOnClose
        >
          <Form
            className={styles.form}
            {...layout}
            name="basic"
            initialValues={{ remember: true }}
            onFinish={onFinish}
          >
            <Form.Item
              label="用户名"
              name="userName"
              rules={[{ required: true, message: '请输入用户名' }]}
              initialValue={isAdd ? '' : initData.userName}
            >
              <Input disabled={isAdd ? false : true} />
            </Form.Item>
            <Form.Item
              label="昵称"
              name="name"
              rules={[{ required: true, message: '请输入昵称' }]}
              initialValue={isAdd ? '' : initData.name}
            >
              <Input />
            </Form.Item>
            <Form.Item
              name="password"
              label="密码"
              rules={[
                {
                  required: isAdd ? true : false,
                  message: '请输入密码',
                },
              ]}
              hasFeedback
            >
              <Input.Password />
            </Form.Item>
            <Form.Item
              name="confirm"
              label="确认密码"
              dependencies={['password']}
              hasFeedback
              rules={[
                {
                  required: isAdd ? true : false,
                  message: '请确认密码',
                },
                ({ getFieldValue }) => ({
                  validator(_, value) {
                    if (!value || getFieldValue('password') === value) {
                      return Promise.resolve();
                    }
                    return Promise.reject(new Error('两次密码输入不一致!'));
                  },
                }),
              ]}
            >
              <Input.Password />
            </Form.Item>
            <Form.Item {...tailLayout}>
              <Button type="primary" htmlType="submit">
                提交
              </Button>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </CardCommon>
  );
};
